﻿using OfficeOpenXml;
using System.Diagnostics;
using System.IO;
using System.Reflection.PortableExecutable;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Brushes = System.Windows.Media.Brushes;
using Button = System.Windows.Controls.Button;
using HorizontalAlignment = System.Windows.HorizontalAlignment;
using Image = System.Windows.Controls.Image;
using Label = System.Windows.Controls.Label;
using MessageBox = System.Windows.MessageBox;
using Orientation = System.Windows.Controls.Orientation;
using Point = System.Windows.Point;

namespace WPF_Preview.PreviewClass
{
    public class ImageWindowManager
    {
        private string cfileName;
        private List<Image> images;
        private List<string> sheetNames;
        private Viewbox imageViewbox; // 用于存放图片
        private Viewbox editViewbox;  // 用于存放编辑网格
        private StackPanel buttonPanel;
        private Window imageWindow;
        private Process excelProcess;
        private List<CustomWorksheet> customWorksheets; // 保存自定义工作表数据
        private int currentSheetIndex = 0; // 当前显示的工作表索引
        private bool isEditing = false;
        private List<DataGrid> editDataGrids = new List<DataGrid>(); // 缓存编辑模式下的 DataGrid

        public ImageWindowManager()
        {
            buttonPanel = new StackPanel
            {
                Orientation = Orientation.Horizontal,
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment = VerticalAlignment.Top,
                Width = 900
            };
            imageViewbox = new Viewbox
            {
                Stretch = Stretch.Uniform
            };
            editViewbox = new Viewbox
            {
                Stretch = Stretch.Uniform
            };
        }

        private void ImageWindow_Closed(object? sender, EventArgs e)
        {
            imageWindow = null;
        }

        /// <summary>
        /// 预览窗口
        /// </summary>
        /// <param name="fileName">当前excel文件路径</param>
        /// <param name="images">生成图片</param>
        /// <param name="sheetNames">当前excel的第几个sheet</param>
        public void ShowImageInNewWindow(string fileName, List<Image> images, List<string> sheetNames, List<CustomWorksheet> customWorksheets)
        {
            this.customWorksheets = customWorksheets;
            cfileName = fileName;
            this.images = images;
            this.sheetNames = sheetNames;

            if (imageWindow == null)
            {
                imageWindow = new Window
                {
                    WindowStartupLocation = WindowStartupLocation.CenterScreen,
                    ResizeMode = ResizeMode.NoResize,
                    Width = 1700,
                    Height = 950,
                    Title = fileName.Split("\\").Last(),
                };
                imageWindow.Closed += ImageWindow_Closed;
            }
            imageWindow.Content = null;
            var buttonPanel = new StackPanel
            {
                Orientation = Orientation.Horizontal,
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment = VerticalAlignment.Top,
                Width = 600
            };
            var checkBoxPanel = new StackPanel
            {
                Orientation = Orientation.Horizontal,
                HorizontalAlignment = HorizontalAlignment.Right,
                VerticalAlignment = VerticalAlignment.Top,
                Width = 700
            };
            var scrollViewer = new ScrollViewer
            {
                HorizontalScrollBarVisibility = ScrollBarVisibility.Auto,
                VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
                Margin = new Thickness(5, 10, 5, 5)
            };

            var grid = new Grid();
            grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
            grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
            Grid.SetRow(buttonPanel, 0);
            Grid.SetRow(checkBoxPanel, 0);
            Grid.SetRow(scrollViewer, 1);
            grid.Children.Add(buttonPanel);
            grid.Children.Add(checkBoxPanel);

            // 将两个 Viewbox 都添加到 ScrollViewer 中
            var viewboxGrid = new Grid();

            // 检查 imageViewbox 是否已有父元素，若有则移除
            if (imageViewbox.Parent != null)
            {
                var parentPanel = imageViewbox.Parent as Panel;
                if (parentPanel != null)
                {
                    parentPanel.Children.Remove(imageViewbox);
                }
            }
            viewboxGrid.Children.Add(imageViewbox);

            // 检查 editViewbox 是否已有父元素，若有则移除
            if (editViewbox.Parent != null)
            {
                var parentPanel = editViewbox.Parent as Panel;
                if (parentPanel != null)
                {
                    parentPanel.Children.Remove(editViewbox);
                }
            }
            viewboxGrid.Children.Add(editViewbox);

            scrollViewer.Content = viewboxGrid;


            var border = new Border();
            border.Background = new SolidColorBrush(System.Windows.Media.Color.FromArgb(0xff, 0xc0, 0xc6, 0xce));
            border.Padding = new Thickness(10, 20, 10, 10);
            grid.Children.Add(scrollViewer);
            imageWindow.Content = grid;

            for (int i = 0; i < sheetNames.Count; i++)
            {
                var button = new Button
                {
                    Content = sheetNames[i],
                    Margin = new Thickness(5, 0, 0, 0),
                    Width = 80,
                    Height = 50,
                    Background = Brushes.CadetBlue,
                };
                int index = i;
                button.Click += (sender, e) =>
                {
                    currentSheetIndex = index;
                    ShowSheet(index);
                };
                buttonPanel.Children.Add(button);
            }
            var newCheckbutton = new Button
            {
                Content = "新建",
                Margin = new Thickness(5, 0, 0, 0),
                Width = 100,
                Height = 50,
                Background = Brushes.CadetBlue,
            };
            newCheckbutton.Click += (sender, e) =>
            {
                try
                {
                    string directoryPath = Path.GetDirectoryName(cfileName);
                    Process.Start("explorer.exe", directoryPath);

                }
                catch (Exception ex)
                {
                    MessageBox.Show($"无法打开 Excel 文件: {ex.Message}");
                }
            };
            var editCheckButton = new Button
            {
                Content = "编辑",
                Margin = new Thickness(5, 0, 0, 0),
                Width = 100,
                Height = 50,
                Background = Brushes.CadetBlue,
            };
            editCheckButton.Click += Btn_Edit_Click;
            var saveButton = new Button
            {
                Content = "保存",
                Margin = new Thickness(5, 0, 0, 0),
                Width = 100,
                Height = 50,
                Background = Brushes.CadetBlue,
                Visibility = Visibility.Collapsed
            };
            saveButton.Click += Btn_Save_Click;
            var refreshButton = new Button
            {
                Content = "刷新",
                Margin = new Thickness(5, 0, 0, 0),
                Width = 100,
                Height = 50,
                Background = Brushes.CadetBlue,
            };
            refreshButton.Click += Btn_Refresh_Click;
            var btn_ValidateRecipe = new Button
            {
                Content = "校验",
                Margin = new Thickness(5, 0, 0, 0),
                Width = 100,
                Height = 50,
                Background = Brushes.CadetBlue,
            };
            btn_ValidateRecipe.Click += Btn_ValidateRecipe_Click;
            Grid gd = new Grid();
            gd.Width = 100;
            gd.Height = 40;
            gd.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Auto) });
            gd.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
            Label label = new Label();
            label.Foreground = Brushes.Black;
            label.HorizontalContentAlignment = HorizontalAlignment.Center;
            label.HorizontalAlignment = HorizontalAlignment.Center;
            label.VerticalAlignment = VerticalAlignment.Center;
            label.Content = "下载配方";
            Grid.SetColumn(label, 1);
            Image image = new Image();
            image.VerticalAlignment = VerticalAlignment.Center;
            image.HorizontalAlignment = HorizontalAlignment.Center;
            image.Width = 20;
            image.Height = 20;
            Grid.SetColumn(image, 0);
            gd.Children.Add(image);
            gd.Children.Add(label);
            var DownLoadButton = new Button
            {
                Content = gd,
                HorizontalContentAlignment = HorizontalAlignment.Center,
                Margin = new Thickness(5, 0, 0, 0),
                Width = 120,
                Height = 50,
                Background = Brushes.CadetBlue,
            };
            DownLoadButton.Click += DownLoadButton_Click;
            checkBoxPanel.Children.Add(newCheckbutton);
            checkBoxPanel.Children.Add(editCheckButton);
            checkBoxPanel.Children.Add(saveButton);
            checkBoxPanel.Children.Add(refreshButton);
            checkBoxPanel.Children.Add(btn_ValidateRecipe);
            checkBoxPanel.Children.Add(DownLoadButton);

            // 默认显示图片预览
            isEditing = false;
            if (images.Count > 0)
            {
                ShowSheet(0);
            }

            Point lastMousePosition;
            bool isDragging = false;
            scrollViewer.MouseLeftButtonDown += (sender, e) =>
            {
                isDragging = true;
                lastMousePosition = e.GetPosition(scrollViewer);
                scrollViewer.CaptureMouse();
            };
            scrollViewer.MouseLeftButtonUp += (sender, e) =>
            {
                isDragging = false;
                scrollViewer.ReleaseMouseCapture();
            };
            scrollViewer.MouseMove += (sender, e) =>
            {
                if (isDragging)
                {
                    Point currentMousePosition = e.GetPosition(scrollViewer);
                    double offsetX = currentMousePosition.X - lastMousePosition.X;
                    double offsetY = currentMousePosition.Y - lastMousePosition.Y;
                    scrollViewer.ScrollToHorizontalOffset(scrollViewer.HorizontalOffset - offsetX);
                    scrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset - offsetY);
                    lastMousePosition = currentMousePosition;
                }
            };

            imageWindow.Show();
            imageWindow.Focus();
        }

        private void ShowSheet(int index)
        {
            if (isEditing)
            {
                // 显示编辑网格
                imageViewbox.Visibility = Visibility.Collapsed;
                editViewbox.Visibility = Visibility.Visible;
                if (editDataGrids.Count > index)
                {
                    editViewbox.Child = editDataGrids[index];
                }
            }
            else
            {
                // 显示图片
                editViewbox.Visibility = Visibility.Collapsed;
                imageViewbox.Visibility = Visibility.Visible;
                if (images.Count > index)
                {
                    imageViewbox.Child = images[index];
                }
            }
        }

        private void EnableEditing()
        {
            var saveButton = GetButtonByName("保存");
            saveButton.Visibility = Visibility.Visible;
            isEditing = true;
            LoadAllEditDataGrids();
            ShowSheet(currentSheetIndex);
        }

        private void LoadAllEditDataGrids()
        {
            editDataGrids.Clear();

            foreach (var customWorksheet in customWorksheets)
            {
                var dataGrid = new DataGrid
                {
                    ItemsSource = GetDataGridItems(customWorksheet),
                    FontSize = 18,
                    AutoGenerateColumns = false,
                    CanUserAddRows = false,
                    CanUserDeleteRows = false,
                    IsReadOnly = false,
                    RowHeaderWidth = 0,
                    HeadersVisibility = DataGridHeadersVisibility.None
                };

                // 设置虚拟化属性
                dataGrid.SetValue(VirtualizingStackPanel.IsVirtualizingProperty, true);
                dataGrid.SetValue(VirtualizingStackPanel.VirtualizationModeProperty, VirtualizationMode.Recycling);

                for (int col = 1; col <= customWorksheet.MaxColumn; col++)
                {
                    var column = new DataGridTextColumn
                    {
                        Header = col.ToString(),
                        Binding = new System.Windows.Data.Binding($"[{col - 1}]")
                    };
                    dataGrid.Columns.Add(column);
                }
                // 处理 CellEditEnding 事件
                dataGrid.CellEditEnding += DataGrid_CellEditEnding;
                editDataGrids.Add(dataGrid);
            }
        }
        private HashSet<(int row, int col)> changedCells = new HashSet<(int row, int col)>();
        private void DataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
        {
            var dataGrid = sender as DataGrid;
            if (dataGrid == null)
            {
                return;
            }
            var rowIndex = dataGrid.Items.IndexOf(e.Row.Item);
            var columnIndex = dataGrid.Columns.IndexOf(e.Column);
            var textBox = e.EditingElement as TextBox;
            if (textBox != null)
            {
                var oldValue = ((List<string>)e.Row.Item)[columnIndex];
                var newValue = textBox.Text;
                if (oldValue != newValue)
                {
                    changedCells.Add((rowIndex, columnIndex));
                    var cell = e.Column.GetCellContent(e.Row)?.Parent as DataGridCell;
                    if (cell != null)
                    {
                        cell.FontSize = 25;
                        cell.Foreground = Brushes.Blue;
                    }
                }
            }
        }

        private List<List<string>> GetDataGridItems(CustomWorksheet customWorksheet)
        {
            var items = new List<List<string>>();
            for (int row = 1; row <= customWorksheet.MaxRow; row++)
            {
                var rowData = new List<string>();
                for (int col = 1; col <= customWorksheet.MaxColumn; col++)
                {
                    var key = (row, col);
                    customWorksheet.Cells.TryGetValue(key, out var value);
                    rowData.Add(value ?? "");
                }
                items.Add(rowData);
            }
            return items;
        }

        private void DisableEditing()
        {
            isEditing = false;
            var saveButton = GetButtonByName("保存");
            saveButton.Visibility = Visibility.Collapsed;
            ShowSheet(currentSheetIndex);
        }

        private Button GetButtonByName(string name)
        {
            var checkBoxPanel = ((Grid)imageWindow.Content).Children.OfType<StackPanel>().Last();
            return checkBoxPanel.Children.OfType<Button>().FirstOrDefault(b => b.Content.ToString() == name);
        }

        private async Task SaveChangesAndUpdateImage()
        {
            try
            {
                using (var package = new ExcelPackage(new FileInfo(cfileName)))
                {
                    var workbook = package.Workbook;
                    // 确保 customWorksheets 列表的数量不超过实际工作表数量
                    int count = Math.Min(customWorksheets.Count, workbook.Worksheets.Count);
                    for (int i = 0; i < count; i++)
                    {
                        var worksheet = workbook.Worksheets[i];
                        var customWorksheet = customWorksheets[i];
                        var dataGrid = editDataGrids[i];
                        var items = (List<List<string>>)dataGrid.ItemsSource;

                        for (int row = 0; row < items.Count; row++)
                        {
                            for (int col = 0; col < items[row].Count; col++)
                            {
                                var key = (row + 1, col + 1);
                                customWorksheet.Cells[key] = items[row][col];
                                worksheet.Cells[row + 1, col + 1].Value = items[row][col];
                            }
                        }
                    }
                    await package.SaveAsync();
                }
                await ExcelPreViewTool.ReadExcelAsync(cfileName, new List<(int, int, int, string)>() { }, this);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存更改失败: {ex.Message}");
            }
        }

        private void Btn_Edit_Click(object sender, RoutedEventArgs e)
        {
            EnableEditing();
        }

        private async void Btn_Save_Click(object sender, RoutedEventArgs e)
        {
            DisableEditing();
            await SaveChangesAndUpdateImage();
        }
        private async void Btn_Refresh_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                await ExcelPreViewTool.ReadExcelAsync(cfileName, new List<(int, int, int, string)>() { }, this);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"刷新 Excel 文件失败: {ex.Message}");
            }
        }

        private async void Btn_ValidateRecipe_Click(object sender, RoutedEventArgs e)
        {
            try
            {
            }
            catch (Exception ex)
            {
                MessageBox.Show($"读取PLC数据失败：{ex.Message}");
            }
        }

        private async void DownLoadButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var valsToPlc = new List<(int, int, int, string)>();
                valsToPlc = await ExcelPreViewTool.ReadExcelAsync(cfileName, new List<(int, int, int, string)>() { }, this);
                WriteDataToPLC(valsToPlc);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"下载配方失败：{ex.Message}");
            }
        }
        private void WriteDataToPLC(List<(int, int, int, string)> valsToPlc)
        {
            try
            {
                MessageBox.Show("下载配方成功！");
            }
            catch
            {

            }
        }
    }
}
